import requests
import json
from time import sleep

API_ROOT = 'https://careerapi.universalbeijingresort.com/api'
API_POSITION = API_ROOT + '/positions'
API_JOB_DETAIL = API_ROOT + '/jobDetail'

REQUEST_CONTENT_TYPE = 'application/json;charset=utf-8'
REQUEST_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'
REQUEST_ACCEPT = 'application/json'

LANGUAGE_EN_US = 'en_US'
LANGUAGE_ZH_CN = 'zh_CN'

def make_headers():
  return {
    'Content-Type': REQUEST_CONTENT_TYPE,
    'User-Agent': REQUEST_USER_AGENT,
    'Accept-Language': LANGUAGE_EN_US,
    'Accept': REQUEST_ACCEPT
  }

def query_positions(page = 1, subcategory = None):
  data = {
    'page': page
  }
  if subcategory is not None:
    data['subcategory'] = subcategory
  try:
    response = requests.post(API_POSITION, data = json.dumps(data), headers = make_headers())
  except:
    print('Request error! ' + str(ex))
    return None
  if response.status_code is not 200:
    print('HTTP request failed, status code: ' + response.status_code)
    return None
  try:
    out = json.loads(response.text)
    # print(out)
  except Exception as ex:
    print('JSON decode error! ' + str(ex))
    print('JSON data: ' + response.text)
    return None
  if out['code'] != 1000:
    print('API query failed, return code: ' + str(out['code']))
    return None
  return out['result']

def query_job_detail(ubr_job_id, language = None):
  h = make_headers()
  if language is not None:
    h['Accept-Language'] = language
  try:
    response = requests.get(API_JOB_DETAIL + '?jobReqId=' + str(ubr_job_id), headers = h, timeout = 10)
    sleep(0.5)
  except Exception as ex:
    print('Request error and will retry: ' + str(ex))
    sleep(10)
    try:
      response = requests.get(API_JOB_DETAIL + '?jobReqId=' + str(ubr_job_id), headers = h, timeout = 15)
    except Exception as ex:
      print('Request error! ' + str(ex))
      return False
  try:
    out = json.loads(response.text)
    # print(out)
  except Exception as ex:
    print('JSON decode error! ' + str(ex))
    print('JSON data: ' + response.text)
    return False
  if out['code'] != 1000:
    print('API query failed, return code: ' + str(out['code']))
    return False
  return out['result']['desc']
